package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author:
 * @description:
 * @keypoint:
 * @tags:
 * @related:
 */

@MappedTypes(Integer[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class IntegerArrayTypeHandler implements TypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 输入映射 也就是插入数据前端传过来的是整型数组类型，插入到数据库String类型
     * @param preparedStatement
     * @param i
     * @param integers
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {

        try {
            String value = objectMapper.writeValueAsString(integers);
            //预编译的按位置提供参数
            preparedStatement.setString(i,value);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * 输出映射，从数据库里面拿出来的String，返回给前端的是整型数组类型
     * @param resultSet
     * @param columName
     * @return
     * @throws SQLException
     */
    @Override
    public Integer[] getResult(ResultSet resultSet, String columName) throws SQLException {
        String result = resultSet.getString(columName);
        Integer[] integers = new Integer[0];
        try {
            integers = objectMapper.readValue(result, Integer[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return integers;
    }

    @Override
    public Integer[] getResult(ResultSet resultSet, int i) throws SQLException {

        String result = resultSet.getString(i);
        Integer[] integers = new Integer[0];
        try {
            integers = objectMapper.readValue(result, Integer[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return integers;
    }

    @Override
    public Integer[] getResult(CallableStatement callableStatement, int i) throws SQLException {
        String result = callableStatement.getString(i);
        Integer[] integers = new Integer[0];
        try {
            integers = objectMapper.readValue(result, Integer[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return integers;
    }

}
